<template>
  <div
    class="DropdownMenu__wrap zIndex"
    :class="{
      'DropdownMenu__wrap--fixed': isFixed,
      'DropdownMenu__wrap--overlay': showOverlay
    }"
    @click.self="hideOverlay"
  >
    <ul
      class="filter-list-wrap"
      :style="{ 'background-color': backgroundColor }"
    >
      <template>
        <li
          v-for="(item, index) in optionsArr"
          :key="index"
          class="filter-item-wrap"
          @click="setActive(item)"
        >
          <div class="li__tab">
            <span
              class="li__text li__text2"
              :class="{ isActive: item.isActive }"
              >{{ item.text }}</span
            >
            <div
              v-if="item.arrowType"
              class="li__icon"
              :class="{
                arrowType1: item.arrowType === 1,
                arrowType1_active: item.arrowType === 1 && item.isActive,
                arrowType2: item.arrowType === 2,
                arrowType2_topActive:
                  item.arrowType === 2 && item.isActive && item.sortRule === 1,
                arrowType2_bottomActive:
                  item.arrowType === 2 && item.isActive && item.sortRule === 2,
                arrowType3: item.arrowType === 3,
                arrowType3_active: item.arrowType === 3 && item.isActive
              }"
            ></div>
          </div>
          <!-- 下拉列表 -->
          <div v-if="item.selectArr" class="li__select">
            <ul v-show="item.showSelect" class="select__ul">
              <li
                v-for="(it, i) in item.selectArr"
                :key="i"
                class="filter-item-wrap"
                :class="{ isActive: it.isActive }"
                @click.stop="selectClick(item, it)"
              >
                {{ it.text }}
              </li>
            </ul>
          </div>
        </li>
      </template>
    </ul>
    <!-- 筛选 -->
    <div v-if="showScreen" class="wrap__screen" @click.stop.self="closeScreen">
      <div class="screen">
        <!-- loading -->
        <div v-if="loading" class="screen__loading">
          <van-loading />
        </div>
        <div v-else class="screen__class">
          <!-- 商品状态 -->
          <div v-if="forecastList.length" class="class__box">
            <div class="box__tit">
              <h3 class="tit--title">
                商品状态
              </h3>
            </div>
            <ul class="box__con">
              <li
                v-for="(cur, i) in forecastList"
                :key="i"
                :class="{ active: cur.isActive }"
                @click.stop="
                  setCheckboxActive({
                    type: 'forecastList',
                    index: i
                  })
                "
              >
                {{ cur.name }}
              </li>
            </ul>
          </div>
          <!-- 品牌 -->
          <div class="class__box">
            <div class="box__tit">
              <h3 class="tit--title">
                选择品牌
              </h3>
              <p>{{ selectedValue }}</p>
            </div>
            <ul v-if="brandSelectList.length" class="box__con">
              <li
                v-for="(cur, i) in brandSelectList"
                :key="i"
                :class="{ active: cur.isActive }"
                @click.stop="
                  setCheckboxActive({
                    type: 'brandSelectList',
                    index: i
                  })
                "
              >
                {{ cur.name }}
              </li>
            </ul>
            <div v-else class="box--empty">
              <img src="../images/search/img-search-no-result2.png" />
            </div>
          </div>
        </div>
        <!-- 底部按钮区 -->
        <div class="screen__fun">
          <div class="fun__button fun__button--reset" @click.stop="resetHandle">
            重置
          </div>
          <div
            class="fun__button fun__button--confirm"
            @click.stop="confirmHandle"
          >
            确认<span>（100款商品）</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    optionsArr: {
      type: Array,
      default: () => []
    },
    isFixed: {
      type: Boolean,
      default: false
    },
    backgroundColor: {
      type: String,
      default() {
        return `linear-gradient(
      180deg,
      rgba(255, 255, 255, 1) 0%,
      rgba(255, 255, 255, 0.79) 62%,
      rgba(255, 255, 255, 0) 100%
    )`;
      }
    },
    brandNameListArr: {
      type: Array,
      default: () => []
    },
    categoryListArr: {
      type: Array,
      default: () => []
    },
    forecastArr: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showOverlay: false,
      showScreen: false,
      brandSelectList: [],
      forecastList: [],
      firstLevelActive: 0,
      productTypeModel: 3,
      lastProductTypeModel: ''
    };
  },
  computed: {
    selectedValue() {
      let str = '';
      if (this.brandSelectList.length > 0) {
        const arr = this.brandSelectList
          .filter(item => item.isActive)
          .map(item => item.name);
        str = arr.join('，');
        // str = str.length > 15 ? `${str.slice(0, 15)}...` : str;
      }
      return str;
    }
  },
  watch: {
    /**
     * https://juejin.cn/post/7017588385615200270
     * JSON.stringify()
     * 1. undefined、任意的函数以及symbol值，出现在【非数组对象】的属性值中时在序列化过程中会被忽略
     * 2. undefined、任意的函数以及symbol值出现在【数组】中时会被转换成 null
     * 3. undefined、任意的函数以及symbol值被【单独转换】时，会返回 undefined
     *
     * 深度拷贝JSON.parse(JSON.stringify(obj)) 缺陷
     * 1. 如果obj里有Date对象，序列化属性时间将只是字符串的形式。而不是时间对象；
     * 2. 如果obj里有RegExp、Error对象，序列化属性为空对象；
     * 3. 如果obj里有function、symbol、undefined，序列化属性会丢失；
     * 4. 如果obj里有NaN、Infinity和-Infinity，序列化属性会变成null
     * 5. JSON.stringify()只能序列化对象的可枚举的自有属性
     * 例如 如果obj中的对象是有构造函数生成的， 则使用JSON.parse(JSON.stringify(obj))深拷贝后，会丢弃对象的constructor；
     * 6. 如果对象中存在循环引用的情况也无法实现深拷贝
     * 例如 let cyclicObj = { name: '前端胖头鱼' }
     * cyclicObj.obj = cyclicObj
     * console.log(JSON.stringify(cyclicObj))
     *
     * JSON.stringify(signInfo, (key, value) => typeof value === 'undefined' ? '' : value)
     */
    /**
     * 第一个是handler 其值是一个回调函数。即监听到变化时应该执行的函数。
     * 第二个是deep：其值是true或false；确认是否深入监听。【一般监听时是不能监听到对象属性值的变化的，数组的值变化可以听到】对象数组需要的
     * 第三个是immediate：其值是true或false；确认是否以当前的初始值执行handler的函数
     */
    brandNameListArr: {
      handler(newVal) {
        console.log('brandNameListArr==', newVal);
        // 方式一赋值 存在性能问题 如果直接赋值，地址指向一样，brandSelectList变化了，brandNameListArr也会跟着变，然后又重新赋值了
        this.brandSelectList = newVal;
        // 方式二赋值
        // this.brandSelectList = JSON.parse(JSON.stringify(newVal));
        // 方式三赋值
        // this.brandSelectList = newVal.map(item => {
        //   return { ...item };
        // });
      },
      immediate: true,
      deep: true
    },
    forecastArr: {
      handler(newVal) {
        this.forecastList = JSON.parse(JSON.stringify(newVal));
      },
      immediate: true,
      deep: true
    },
    showOverlay(newVal) {
      if (newVal) {
        document.body.addEventListener('touchmove', this.stopDefault, {
          passive: false
        });
      } else {
        document.body.removeEventListener('touchmove', this.stopDefault, {
          passive: false
        });
      }
    }
  },
  deactivated() {
    document.body.removeEventListener('touchmove', this.stopDefault, {
      passive: false
    });
  },
  beforeDestroy() {
    document.body.removeEventListener('touchmove', this.stopDefault, {
      passive: false
    });
  },
  methods: {
    stopDefault(event) {
      event.preventDefault();
    },
    setActive(obj) {
      this.$emit('getSort', obj);
      // 若点击是筛选按钮
      if (Number(obj.value) === 6) {
        this.showScreen = true;
      }
    },
    selectClick(obj, item) {
      const selectItem = obj.selectArr.filter(it => it.isActive);
      if (selectItem.length > 0 && selectItem[0].value === item.value) {
        return;
      }
      // 会影响外部数据
      obj.selectArr.forEach(cur => {
        cur.isActive = cur.value === item.value;
      });
      this.$emit('getSort', { ...obj, sortedModel: item.value });
      this.showOverlay = false;
    },
    hideOverlay() {
      this.showOverlay = false;
      this.optionsArr.forEach(item => {
        if (item.selectArr) {
          item.showSelect = false;
        }
      });
    },
    setCheckboxActive(obj) {
      const { type, index } = obj || {};
      if (type === 'brandSelectList') {
        // 对应监听brandNameListArr方案一
        this.brandSelectList = this.brandSelectList.map((item, idx) => {
          return { ...item, isActive: idx === index };
        });
        // 对应监听brandNameListArr方案二、三
        // this.brandSelectList = this.brandSelectList.map((item, idx) => {
        //   item.isActive = idx === index;
        //   return item;
        // });
        console.log(this.brandNameListArr, this.brandSelectList);
        this.$emit(
          'setCheckboxActive',
          this.brandSelectList,
          this.forecastList
        );
      } else if (type === 'forecastList') {
        // 选择商品状态
        this.forecastList = this.forecastList.map((item, idx) => {
          item.isActive = idx === index;
          if (idx === index) {
            this.productTypeModel = item.type;
          }
          return item;
        });
        this.$emit('updateBrandList', this.productTypeModel);
      }
    },
    clearData() {
      const bool = this.brandNameListArr.some(item => item.isActive);
      const forecastBool = this.forecastArr.some(item => item.isActive);
      if (!bool) {
        this.brandSelectList = this.brandSelectList.map(item => {
          item.isActive = false;
          return item;
        });
      } else {
        this.brandSelectList = JSON.parse(
          JSON.stringify(this.brandNameListArr)
        );
      }
      if (!forecastBool) {
        this.forecastList = this.forecastList.map(item => {
          item.isActive = false;
          return item;
        });
      } else {
        this.forecastList = JSON.parse(JSON.stringify(this.forecastArr));
      }
    },
    closeScreen() {
      this.clearData();
      this.showScreen = false;
      this.$emit('closeScreen', this.brandSelectList);
    },
    setShowScreen(boo) {
      this.showScreen = boo;
    },
    resetHandle() {
      this.brandSelectList = this.brandSelectList.map(item => {
        item.isActive = false;
        return item;
      });
      this.forecastList = this.forecastList.map(item => {
        item.isActive = false;
        return item;
      });
      this.$emit('resetActive');
    },
    confirmHandle() {
      this.setShowScreen(false);
      this.$emit('confirm', this.brandSelectList, this.forecastList);
    }
  }
};
</script>

<style lang="scss" scoped>
.DropdownMenu__wrap {
  position: relative;
  z-index: 999;
  width: 100%;
  border-radius: 10px 10px 0 0;
  &.zIndex {
    z-index: 2000;
  }

  .filter-list-wrap {
    display: flex;
    justify-content: space-around;
    background: linear-gradient(
      180deg,
      rgba(255, 255, 255, 1) 0%,
      rgba(255, 255, 255, 0.79) 62%,
      rgba(255, 255, 255, 0) 100%
    );
    border-radius: 10px 10px 0 0;
    .filter-item-wrap {
      flex: 1;
      .li__tab {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 45px;
        /*line-height: 45px;*/

        .li__text {
          padding-right: 3px;
          font-size: 14px;
          color: #666;
        }
        .li__text2 {
          padding-right: 3px;
          font-size: 14px;
          color: #333;
        }

        .isActive {
          color: #e40000;
          // color: #ff1010;
        }

        .li__icon {
          display: flex;
          flex-direction: column;
          width: 10px;
          height: 45px;
          background-position: center;
          background-repeat: no-repeat;
          background-size: contain;
        }

        .arrowType1 {
          background-image: url('../images/icon_arrowType1.png');
        }
        .arrowType1_active {
          background-image: url('../images/icon_arrowType1_active.png');
        }
        .arrowType2 {
          //background-image: url('../images/icon_arrowType2.png');
          background-image: url('../images/icon_arrowType22.png');
        }
        .arrowType2_topActive {
          //background-image: url('../images/icon_arrowType2_topActive.png');
          background-image: url('../images/icon_arrowType22_topActive.png');
        }
        .arrowType2_bottomActive {
          //background-image: url('../images/icon_arrowType2_bottomActive.png');
          background-image: url('../images/icon_arrowType22_bottomActive.png');
        }
        .arrowType3 {
          background-image: url('../images/icon_arrowType3.png');
        }
        .arrowType3_active {
          background-image: url('../images/icon_arrowType3_active.png');
        }
      }

      .li__select {
        position: absolute;
        left: 0;
        width: 100%;

        .select__ul {
          overflow: hidden;
          border-radius: 0 0 6px 6px;

          .filter-item-wrap {
            padding: 10px 25px;
            background-color: #fff;
            font-size: 14px;
            color: #333;
          }

          .isActive {
            color: #e40000;
          }
        }
      }
    }
  }

  .wrap__screen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.2);
    z-index: 99;
    .screen {
      position: fixed;
      top: 0;
      right: 0;
      width: 315px;
      height: 100vh;
      background-color: #fff;
      border-top-left-radius: 6px;
      border-bottom-left-radius: 6px;
      overflow-y: scroll;

      .screen__class {
        padding-bottom: 56px;

        .class__box {
          padding: 16px 4px 12px 5px;
          background-color: #fff;
          border-radius: 12px;

          .box__tit {
            padding: 0 4px 5px 7px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 14px;
            color: #333;

            .tit--title {
              font-weight: normal;
              font-size: 16px;
            }

            p {
              font-size: 11px;
              color: #999;
              text-align: right;
              width: 206px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
          .box__con {
            display: flex;
            flex-wrap: wrap;
            // padding: 0 10px;

            li {
              flex-shrink: 0;
              padding: 0 5px;
              margin: 5px;
              width: 92px;
              height: 30px;
              font-size: 12px;
              color: #333;
              text-align: center;
              line-height: 30px;
              background-color: #f5f5f5;
              border: 1px solid transparent;
              border-radius: 18px;
              box-sizing: border-box;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .active {
              color: #ff1010;
              background-color: #ffebeb;
              border: 1px solid #ff1010;
              /*font-family: PingFangSC-Medium;*/
              font-weight: 500;
            }
          }

          .box--empty {
            padding-top: 109px;
            color: #ccc;

            img {
              width: 240px;
              margin: 0 auto;
            }

            p {
              font-size: 13px;
              font-family: PingFangSC-Medium;
              font-weight: 500;
              text-align: center;
              margin-top: 26px;
            }
          }
        }
      }

      .screen__fun {
        padding: 10px 10px;
        position: fixed;
        bottom: 0;
        right: 0;
        z-index: 10;
        width: inherit;
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        background-color: #fff;
        box-sizing: border-box;
        border-top: 0.5px solid #efefef;
        border-bottom-left-radius: 6px;

        .fun__button {
          height: 36px;
          line-height: 36px;
          text-align: center;
          border-radius: 25px;
          box-sizing: border-box;
        }

        .fun__button--reset {
          width: 102px;
          color: #333;
          border: 0.5px solid #ccc;
        }

        .fun__button--confirm {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 183px;
          color: #fff;
          background-color: #ff1010;

          span {
            font-size: 10px;
          }
        }
      }

      .screen__loading {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
        width: 35px;
        height: 35px;
      }
    }
  }
}

.DropdownMenu__wrap--fixed {
  position: fixed;
  top: 0;
  left: 0;
  border-radius: 0;
  z-index: 2000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);

  .filter-list-wrap {
    background-color: #fff !important;
    border-radius: 0;
  }
}

.DropdownMenu__wrap--overlay {
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  overflow: hidden;

  .filter-list-wrap {
    background-color: #fff !important;
    border-radius: 0;
  }
}
</style>
